package com.sls.game.service.impl;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.ServerDateAndTime;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.assist.Helper;
import com.sls.game.common.DeductionRefund;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.DownstreamUserDAO;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.dao.GoodsOrderLogDAO;
import com.sls.game.dao.GoodsSupplyManageDAO;
import com.sls.game.dao.xingxitian.XingAccountTypeDAO;
import com.sls.game.dao.xingxitian.XingChargeTypeDAO;
import com.sls.game.dao.xingxitian.XingDisCountDAO;
import com.sls.game.dao.xingxitian.XingGameAreaSrvDAO;
import com.sls.game.dao.xingxitian.XingGoodsTopDAO;
import com.sls.game.dao.xingxitian.XingParvalueDAO;
import com.sls.game.page.Pagination;
import com.sls.game.parser.sls.OrderStatusSendParse;
import com.sls.game.parser.xingqitian.ParseOrderStatusResMsg;
import com.sls.game.parser.xingqitian.XingConfigRead;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.DownstreamUserInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsOrderLog;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.pojo.xingqitian.XingAccountTypeInfo;
import com.sls.game.pojo.xingqitian.XingChargeTypeInfo;
import com.sls.game.pojo.xingqitian.XingConfigInfo;
import com.sls.game.pojo.xingqitian.XingDisCountInfo;
import com.sls.game.pojo.xingqitian.XingGameAreaSrvInfo;
import com.sls.game.pojo.xingqitian.XingGoodsTopInfo;
import com.sls.game.pojo.xingqitian.XingOrderStatusInfo;
import com.sls.game.pojo.xingqitian.XingOrderStatusResMsgInfo;
import com.sls.game.pojo.xingqitian.XingParvalueInfo;
import com.sls.game.service.XingGoodsManagerService;
import com.sls.game.supply.deal.XingQiTianTradeOfDeal;

/**
 * 
 * @description 星启天商品管理
 * @author Wangxuegang
 * @date 2012-12-22
 */
@Service("xingGoodsManagerService")
public class XingGoodsManagerServiceImpl implements XingGoodsManagerService {

	private static Logger log = Logger
			.getLogger(XingGoodsManagerServiceImpl.class);

	private Gson gson = null;

	public XingGoodsManagerServiceImpl() {
		gson = new Gson();
	}

	private XingAccountTypeDAO xingAccountTypeDAO;

	private XingChargeTypeDAO xingChargeTypeDAO;

	private XingDisCountDAO xingDisCountDAO;

	private XingGameAreaSrvDAO xingGameAreaSrvDAO;

	private XingGoodsTopDAO xingGoodsTopDAO;

	private XingParvalueDAO xingParvalueDAO;

	private GoodsOrderDAO goodsOrderDAO;

	private GoodsOrderLogDAO goodsOrderLogDAO;

	private GoodsSupplyManageDAO goodsSupplyManageDAO;

	private DownstreamUserDAO downstreamUserDAO;

	public DownstreamUserDAO getDownstreamUserDAO() {
		return downstreamUserDAO;
	}

	@Resource(name = "downstreamUserDAO")
	public void setDownstreamUserDAO(DownstreamUserDAO downstreamUserDAO) {
		this.downstreamUserDAO = downstreamUserDAO;
	}

	public GoodsSupplyManageDAO getGoodsSupplyManageDAO() {
		return goodsSupplyManageDAO;
	}

	@Resource(name = "goodsSupplyManageDAO")
	public void setGoodsSupplyManageDAO(
			GoodsSupplyManageDAO goodsSupplyManageDAO) {
		this.goodsSupplyManageDAO = goodsSupplyManageDAO;
	}

	public GoodsOrderLogDAO getGoodsOrderLogDAO() {
		return goodsOrderLogDAO;
	}

	@Resource(name = "goodsOrderLogDAO")
	public void setGoodsOrderLogDAO(GoodsOrderLogDAO goodsOrderLogDAO) {
		this.goodsOrderLogDAO = goodsOrderLogDAO;
	}

	public GoodsOrderDAO getGoodsOrderDAO() {
		return goodsOrderDAO;
	}

	@Resource(name = "goodsOrderDAO")
	public void setGoodsOrderDAO(GoodsOrderDAO goodsOrderDAO) {
		this.goodsOrderDAO = goodsOrderDAO;
	}

	public XingAccountTypeDAO getXingAccountTypeDAO() {
		return xingAccountTypeDAO;
	}

	@Resource(name = "xingAccountTypeDAO")
	public void setXingAccountTypeDAO(XingAccountTypeDAO xingAccountTypeDAO) {
		this.xingAccountTypeDAO = xingAccountTypeDAO;
	}

	public XingChargeTypeDAO getXingChargeTypeDAO() {
		return xingChargeTypeDAO;
	}

	@Resource(name = "xingChargeTypeDAO")
	public void setXingChargeTypeDAO(XingChargeTypeDAO xingChargeTypeDAO) {
		this.xingChargeTypeDAO = xingChargeTypeDAO;
	}

	public XingDisCountDAO getXingDisCountDAO() {
		return xingDisCountDAO;
	}

	@Resource(name = "xingDisCountDAO")
	public void setXingDisCountDAO(XingDisCountDAO xingDisCountDAO) {
		this.xingDisCountDAO = xingDisCountDAO;
	}

	public XingGameAreaSrvDAO getXingGameAreaSrvDAO() {
		return xingGameAreaSrvDAO;
	}

	@Resource(name = "xingGameAreaSrvDAO")
	public void setXingGameAreaSrvDAO(XingGameAreaSrvDAO xingGameAreaSrvDAO) {
		this.xingGameAreaSrvDAO = xingGameAreaSrvDAO;
	}

	public XingGoodsTopDAO getXingGoodsTopDAO() {
		return xingGoodsTopDAO;
	}

	@Resource(name = "xingGoodsTopDAO")
	public void setXingGoodsTopDAO(XingGoodsTopDAO xingGoodsTopDAO) {
		this.xingGoodsTopDAO = xingGoodsTopDAO;
	}

	public XingParvalueDAO getXingParvalueDAO() {
		return xingParvalueDAO;
	}

	@Resource(name = "xingParvalueDAO")
	public void setXingParvalueDAO(XingParvalueDAO xingParvalueDAO) {
		this.xingParvalueDAO = xingParvalueDAO;
	}

	/**
	 * 商品详细头部内容表--插入记录
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfGoodsTop(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingGoodsTopInfo info = gson.fromJson(body, XingGoodsTopInfo.class);

		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);

		try {
			xingGoodsTopDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/**
	 * 星启天面额信息表--插入记录
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfParvalue(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingParvalueInfo info = gson.fromJson(body, XingParvalueInfo.class);
		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);
		info.setIsAudit("0");
		String goodsId = this.goodsIdGenerator();
		info.setGoodsId(goodsId);
		try {
			xingParvalueDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/**
	 * 商品编号产生器
	 * 
	 * @return
	 */
	private String goodsIdGenerator() {
		String goodsId = this.xingParvalueDAO.queryMaxGoodsId();

		if (StringUtils.isEmpty(goodsId)) {
			goodsId = "200000000";
		} else {
			int code = Integer.parseInt(goodsId);
			goodsId = String.valueOf(code + 1);
		}
		return goodsId;
	}

	/**
	 * 星启天充值类型表--记录插入
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfChargeType(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingChargeTypeInfo info = gson.fromJson(body, XingChargeTypeInfo.class);
		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);

		try {
			xingChargeTypeDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/**
	 * 星启天账户类型表--记录插入
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfAccountType(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingAccountTypeInfo info = gson.fromJson(body,
				XingAccountTypeInfo.class);
		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);

		try {
			xingAccountTypeDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/**
	 * 记录插入
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfAreaSrv(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingGameAreaSrvInfo info = gson.fromJson(body,
				XingGameAreaSrvInfo.class);
		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);

		try {
			xingGameAreaSrvDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/**
	 * 插入记录
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfDiscount(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingDisCountInfo info = gson.fromJson(body, XingDisCountInfo.class);
		info.setId(UUID.randomUUID().toString());
		String insertTime = ServerDateAndTime.getNowDateTimeOfFormat();
		info.setInsertTime(insertTime);

		try {
			this.xingDisCountDAO.insert(info);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfGoodsTop(java
	 * .lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingGoodsTopInfo> queryByPageOfGoodsTop(String body,
			Head head) throws ServerDisponseException {
		XingGoodsTopInfo topInfo = gson.fromJson(body, XingGoodsTopInfo.class);
		this.validate(topInfo);
		try {
			Pagination<XingGoodsTopInfo> page = this.xingGoodsTopDAO
					.queryGoodsTopInfo(topInfo);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfParvalue(java
	 * .lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingParvalueInfo> queryByPageOfParvalue(String body,
			Head head) throws ServerDisponseException {
		XingParvalueInfo parvalue = gson.fromJson(body, XingParvalueInfo.class);
		this.validate(parvalue);
		try {
			Pagination<XingParvalueInfo> page = this.xingParvalueDAO
					.queryParvalueInfo(parvalue);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfChargeType(
	 * java.lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingChargeTypeInfo> queryByPageOfChargeType(String body,
			Head head) throws ServerDisponseException {
		XingChargeTypeInfo chargeType = gson.fromJson(body,
				XingChargeTypeInfo.class);
		this.validate(chargeType);
		try {
			Pagination<XingChargeTypeInfo> page = this.xingChargeTypeDAO
					.queryChargeTypeInfo(chargeType);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfAccountType
	 * (java.lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingAccountTypeInfo> queryByPageOfAccountType(
			String body, Head head) throws ServerDisponseException {
		XingAccountTypeInfo account = gson.fromJson(body,
				XingAccountTypeInfo.class);
		this.validate(account);
		try {
			Pagination<XingAccountTypeInfo> page = this.xingAccountTypeDAO
					.queryAccountTypeInfo(account);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfAreaSrv(java
	 * .lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingGameAreaSrvInfo> queryByPageOfAreaSrv(String body,
			Head head) throws ServerDisponseException {
		XingGameAreaSrvInfo areaSer = gson.fromJson(body,
				XingGameAreaSrvInfo.class);
		this.validate(areaSer);
		try {
			Pagination<XingGameAreaSrvInfo> page = this.xingGameAreaSrvDAO
					.queryAreaServerInfo(areaSer);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryByPageOfDiscount(java
	 * .lang.String, com.sls.core.socket.Head)
	 */
	@Override
	public Pagination<XingDisCountInfo> queryByPageOfDiscount(String body,
			Head head) throws ServerDisponseException {
		XingDisCountInfo discount = gson.fromJson(body, XingDisCountInfo.class);
		this.validate(discount);
		try {
			Pagination<XingDisCountInfo> page = this.xingDisCountDAO
					.queryDiscountInfo(discount);
			return page;
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#updateSalePrice(java.lang
	 * .String, com.sls.core.socket.Head)
	 */
	@Override
	public void updateSalePrice(String body, Head head)
			throws ServerDisponseException {
		XingDisCountInfo disInfo = gson.fromJson(body, XingDisCountInfo.class);
		this.validate(disInfo);
		if (StringUtils.isEmpty(disInfo.getRecordProid())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.XQT_PRODUCT_ID_EMPTY.getCode(),
					ExceptionCodeDes.XQT_PRODUCT_ID_EMPTY.getDescription());
		}
		String salePrice = disInfo.getRecordSalePrice();
		List<String> ids = this.xingDisCountDAO.queryIdsByProductId(disInfo
				.getRecordProid());
		if (ids != null && !ids.isEmpty()) {
			for (String id : ids) {
				if (StringUtils.isNotEmpty(id)) {
					XingDisCountInfo discount = new XingDisCountInfo();
					discount.setId(id);
					discount.setRecordSalePrice(salePrice);
					this.xingDisCountDAO.updateSalePrice(discount);
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sls.game.service.XingGoodsManagerService#queryParvalueById(java.lang
	 * .String, com.sls.core.socket.Head)
	 */
	@Override
	public XingParvalueInfo queryParvalueById(String body, Head head)
			throws ServerDisponseException {
		XingParvalueInfo info = gson.fromJson(body, XingParvalueInfo.class);
		this.validate(info);
		String id = info.getParvalueId();
		if (StringUtils.isEmpty(id)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ID_EMPTY.getCode(),
					ExceptionCodeDes.ID_EMPTY.getDescription());
		}
		XingParvalueInfo info2 = this.xingParvalueDAO.queryParvalueById(id);
		if (info2 != null) {
			return info2;
		}
		return null;
	}

	/**
	 * 校验是否为空
	 * 
	 * @param obj
	 */
	private void validate(Object obj) {
		if (obj == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
	}

	/**
	 * 异步充值订单状态变化通知接口
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertOfOrderStatus(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingOrderStatusInfo info = gson.fromJson(body,
				XingOrderStatusInfo.class);
		boolean flag = checkDataOfOrderStatus(info);

		// 订单处理结果主动给下游
		String userhandleResult = sendUserOrderStatus(info);

		if (flag) {
			// 更新订单表
			updateGoodsorderInfo(info, head, userhandleResult);
		}

		return null;
	}

	/**
	 * 主动给下游
	 * 
	 * @param info
	 */
	private String sendUserOrderStatus(XingOrderStatusInfo info) {
		String handleResult = "FAILED";
		// 下游回调地址
		String notifyUrl = null;
		// 下游用户编号
		String contractId = null;
		// 手拉手订单编号
		String orderId = info.getTranid();
		GoodsOrderInfo goodsOrderInfo = null;
		goodsOrderInfo = goodsOrderDAO.queryNotifyUrlByOrderId(orderId);
		if (goodsOrderInfo != null) {
			notifyUrl = goodsOrderInfo.getNotifyUrl();
			contractId = goodsOrderInfo.getContractId();
		}

		String secretKey = null; // 下游用户密钥
		DownstreamUserInfo downstreamUserInfo = null;
		downstreamUserInfo = downstreamUserDAO.queryUserByUserNO(contractId);
		if (downstreamUserInfo != null) {
			secretKey = downstreamUserInfo.getSecretKey();
		}

		String parameter = obtainParameter(info, goodsOrderInfo, secretKey);
		String url = notifyUrl + "?" + parameter;
		HttpClient httpClient = new HttpClient();
		// 供应商返回消息编码方式
		String supplyEncode = "UTF-8";
		// 给下游发消息
		try {
			// 给下游发消息
			String xmlStr = httpClient.doGet(url, supplyEncode);

			log.info("异步推送下游返回内容：" + xmlStr);
			if (xmlStr != null && !("".equals(xmlStr))) {
				SLSHttpInterfaceInfo slsInfo = null;
				slsInfo = OrderStatusSendParse.readUserSendMsg(xmlStr);
				if (slsInfo != null) {
					handleResult = slsInfo.getHandleResult();
				}
			}
		} catch (Exception e) {
			log.error(e);
		}

		return handleResult;
	}

	/**
	 * 创建参数字符串
	 * 
	 * @param info
	 * @param goodsOrderInfo
	 * @return
	 */
	private String obtainParameter(XingOrderStatusInfo info,
			GoodsOrderInfo goodsOrderInfo, String secretKey) {
		// 下游用户订单号
		String ptOrderNo = goodsOrderInfo.getMerchantOrderId();
		// 手拉手订单号
		String supOrderNo = info.getTranid();
		// 充值后状态
		String stateCode = info.getState();
		// 成功处理时间
		String ordersuccesstime = goodsOrderInfo.getSupOrderSuccessTime();

		String logCodmsg = null;
		if ("1".equals(stateCode)) { // 成功
			logCodmsg = "成功";
		} else if ("2".equals(stateCode)) { // 失败
			logCodmsg = "失败";
		}
		log.info("星启天异步推送过来的订单处理结果：  \n手拉手订单号:" + supOrderNo + "充值后状态:"
				+ logCodmsg + "处理时间:" + ordersuccesstime);
		StringBuilder strBui = new StringBuilder();
		strBui.append("ptOrderNo=");
		strBui.append(ptOrderNo);
		strBui.append("&");
		strBui.append("supOrderNo=");
		strBui.append(supOrderNo);
		strBui.append("&");
		strBui.append("status=");

		String status = null;
		if ("1".equals(stateCode)) { // 成功
			status = "ORDER_SUCCESS";
		} else if ("2".equals(stateCode)) { // 失败
			status = "ORDER_FAILED";
		}

		strBui.append(status);
		strBui.append("&");

		if ("ORDER_SUCCESS".equals(status)) {
			strBui.append("supOrderSuccessTime=");
			strBui.append(ordersuccesstime);
			strBui.append("&");
		}

		strBui.append("sign=");
		String sign = createSign(ptOrderNo, supOrderNo, status,
				ordersuccesstime, secretKey);
		strBui.append(sign);

		log.info("异步发送给下游用户的订单处理结果    \n 合作方订单编号:" + ptOrderNo + "\n 手拉手订单编号:"
				+ supOrderNo + "\n 订单最终处理结果：" + status + "\n订单处理的时间:"
				+ ordersuccesstime);

		String result = strBui.toString().trim();
		return result;
	}

	/**
	 * 创建签名字符串
	 * 
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param status
	 * @param supOrderSuccessTime
	 * @return
	 */
	private String createSign(String ptOrderNo, String supOrderNo,
			String status, String supOrderSuccessTime, String secretKey) {
		StringBuilder strBui = new StringBuilder();
		strBui.append(ptOrderNo);
		strBui.append(supOrderNo);
		strBui.append(status);
		if (supOrderSuccessTime != null && !("".equals(supOrderSuccessTime))) {
			strBui.append(supOrderSuccessTime);
		}

		strBui.append(secretKey);
		String data = strBui.toString().trim();
		String result = null;
		result = UtilMD5Encryption.createMD5Encryption(data);

		return result;
	}

	/**
	 * 
	 * @param info
	 * @return
	 */
	private boolean checkDataOfOrderStatus(XingOrderStatusInfo info) {
		String state = info.getState();
		String exchange_no = info.getExchange_no();
		String tranid = info.getTranid();
		String sign = info.getSign();
		String ordermoney = info.getOrdermoney();

		log.info("星启天回调推送订单处理结果：" + "\n订单最终处理结果：" + state + "\n星启天订单号："
				+ exchange_no + "\n手拉手订单号：" + tranid + "\n签名字符串：" + sign
				+ "\n订单金额：" + ordermoney);
		boolean flag = false;
		if (state == null || "".equals(state)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ORDER_STATUS_NULL.getCode(),
					ExceptionCodeDes.ORDER_STATUS_NULL.getDescription());
		} else if (exchange_no == null || "".equals(exchange_no)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SUP_ORDER_NO_NULL.getCode(),
					ExceptionCodeDes.SUP_ORDER_NO_NULL.getDescription());
		} else if (tranid == null || "".equals(tranid)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERNO_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERNO_NULL.getDescription());
		} else if (sign == null || "".equals(sign)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SIG_NATURE_NULL.getCode(),
					ExceptionCodeDes.SIG_NATURE_NULL.getDescription());
		} else if (ordermoney == null || "".equals(ordermoney)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TRADE_AMOUNT_NULL.getCode(),
					ExceptionCodeDes.TRADE_AMOUNT_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 根据交易返回的结果更新订单表
	 * 
	 * @param head
	 * 
	 * @param info
	 * 
	 */
	private void updateGoodsorderInfo(XingOrderStatusInfo info, Head head,
			String userhandleResult) {
		// 手拉手订单号
		String tranid = info.getTranid();
		// 星启天订单号
		String exchange_no = info.getExchange_no();
		String state = info.getState();
		String remark = info.getRemark();
		String supOrderSuccessTime = null;

		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		goodsOrderInfo.setOrderId(tranid);
		goodsOrderInfo.setSupOrderId(exchange_no);
		goodsOrderInfo.setResult(state);
		goodsOrderInfo.setStatusRemark(remark);

		String statusValue = "1";
		if ("1".equals(state)) { // 充值成功
			statusValue = "1";
			supOrderSuccessTime = ServerDateAndTime.getNowDateTime();
		} else if ("2".equals(state)) { // 充值失败
			statusValue = "0";

			// 退款操作
			DeductionRefundInfo dedInfo = null;
			dedInfo = DeductionRefund.refundWhenAsynCallBackFailed(tranid,
					goodsOrderDAO, head);
			String paymentStatus = "";
			if (dedInfo != null) {
				paymentStatus = dedInfo.getPaymentStatus();
			}

			if ("1".equals(paymentStatus)) { // 退款成功
				goodsOrderInfo.setIsPay("3"); // 退款成功

				// 退款成功，通知下游用户
				DeductionRefund.noticeUserRefundMsg(tranid, dedInfo,
						goodsOrderDAO, downstreamUserDAO, goodsOrderLogDAO);

			} else if ("2".equals(paymentStatus)) { // 退款失败
				GoodsOrderInfo orderInfo = goodsOrderDAO.queryByOrderId(tranid);
				if (orderInfo != null) {
					String isPayValue = orderInfo.getIsPay(); // 支付状态值
					if ("1".equals(isPayValue)) {
						goodsOrderInfo.setIsPay("2"); // 退款失败
					}
				}
			}
		}
		goodsOrderInfo.setStatus(statusValue);
		goodsOrderInfo.setSupOrderSuccessTime(supOrderSuccessTime);
		goodsOrderInfo.setUserhandleResult(userhandleResult);
		goodsOrderInfo.setSynOrAsy("1"); // 异步推送

		// 数据更新
		try {
			goodsOrderDAO.update(goodsOrderInfo);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		// 写订单日志
		try {
			String orderId = tranid;
			GoodsOrderInfo goodsOrderInfo1 = new GoodsOrderInfo();
			goodsOrderInfo1 = this.goodsOrderDAO.queryByOrderId(orderId);
			if (goodsOrderInfo1 != null) {
				GoodsOrderLog orderLog = Helper.copy(goodsOrderInfo1);
				orderLog.setId(UUID.randomUUID().toString());
				orderLog.setModifyTime(ServerDateAndTime
						.getNowDateTimeOfFormat());
				this.goodsOrderLogDAO.insert(orderLog);
			}

		} catch (Exception e) {
			log.error(e.toString());
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

	}

	/**
	 * 支付订单状态查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String saveQueryOrderStatus(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingOrderStatusInfo info = gson.fromJson(body,
				XingOrderStatusInfo.class);

		boolean flag = checkDataOfQueryOrderStatus(info);
		if (flag) {
			XingOrderStatusResMsgInfo msgInfo = null;
			info.setTranid(info.getTranid().trim());
			msgInfo = dealOrderQueryMsg(info);
			if (msgInfo != null) {
				String state = msgInfo.getState();
				if ("errcode".equals(state)) { // 订单查询失败
					String resultBody = null;
					resultBody = gson.toJson(msgInfo);
					return resultBody;
				} else { // 订单查询成功
					GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
					goodsOrderInfo.setOrderId(msgInfo.getTranidValue());
					goodsOrderInfo.setResult(msgInfo.getStateValue());
					goodsOrderInfo.setSupOrderId(msgInfo.getExchange_noValue());

					// String status = "2"; // 0：失败 1：成功 2：处理中 3：存疑 4 ：冲销 5:
					// 订单不存在
					// // 6: 其它
					// String stateValue = msgInfo.getStateValue();
					// if ("0".equals(stateValue)) { // 订单正在处理中
					// status = "2";
					//
					// } else if ("1".equals(stateValue)) { // 订单充值成功
					// status = "1";
					//
					// } else if ("2".equals(stateValue)) { // 订单充值失败
					// status = "0";
					// }

					// goodsOrderInfo.setStatus(status);
					// updateGoodsOrder(msgInfo.getTranidValue(), head,
					// goodsOrderInfo);

					String resultBody = null;
					resultBody = gson.toJson(msgInfo);
					return resultBody;
				}
			}
		}

		return null;
	}

	/**
	 * 
	 * @param info
	 * @return
	 */
	private XingOrderStatusResMsgInfo dealOrderQueryMsg(XingOrderStatusInfo info) {
		XingOrderStatusResMsgInfo msgInfo = null;
		String merchantid = info.getMerchantid();
		// 手拉手订单号
		String tranid = info.getTranid();
		// 充值游戏账号
		String gameAccount = null;
		String orderQueryAddr = null; // 订单查询地址
		String userKey = null; // 密钥
		XingConfigInfo xingConfigInfo = null;
		xingConfigInfo = XingConfigRead.readConfig();
		if (xingConfigInfo != null) {
			orderQueryAddr = xingConfigInfo.getOrderQueryAddr().trim();
			userKey = xingConfigInfo.getUserKey().trim();
		}

		// 签名字符串
		String sign = XingQiTianTradeOfDeal.createSignOfOrderQuery(merchantid,
				tranid, gameAccount, userKey);

		// 请求url（订单结果查询）
		String url = createUrlOfQueryOrderStatus(info, gameAccount,
				orderQueryAddr, sign);
		HttpClient httpClient = new HttpClient();
		String supplyEncode = "GB2312";
		try {
			String xmlStr = httpClient.doGet(url, supplyEncode);
			msgInfo = ParseOrderStatusResMsg.parseMsgOfOrderStatus(xmlStr);

		} catch (Exception e) {
			log.error(e);
		}

		return msgInfo;
	}

	/**
	 * 拼装订单结果查询url
	 * 
	 * @param info
	 * @param gameAccount
	 * @param orderQueryAddr
	 * @param sign
	 * @return
	 */
	private String createUrlOfQueryOrderStatus(XingOrderStatusInfo info,
			String gameAccount, String orderQueryAddr, String sign) {
		String merchantid = info.getMerchantid();
		String tranid = info.getTranid();

		StringBuilder strBui = new StringBuilder();
		strBui.append(orderQueryAddr);
		strBui.append("?");
		strBui.append("merchantid=");
		strBui.append(merchantid);
		strBui.append("&");
		strBui.append("tranid=");
		strBui.append(tranid);
		strBui.append("&");
		strBui.append("playerusername=");
		strBui.append(gameAccount);
		strBui.append("&");
		strBui.append("sign=");
		strBui.append(sign);

		String url = strBui.toString().trim();
		return url;
	}

	/**
	 * 校验
	 * 
	 * @param info
	 * @return
	 */
	private boolean checkDataOfQueryOrderStatus(XingOrderStatusInfo info) {
		// 商户ID
		String merchantid = info.getMerchantid();
		// 手拉手订单号
		String tranid = info.getTranid();
		boolean flag = false;
		if (merchantid == null || "".equals(merchantid)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.USER_ID_NULL.getCode(),
					ExceptionCodeDes.USER_ID_NULL.getDescription());
		} else if (tranid == null || "".equals(tranid)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERID_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERID_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	private boolean checkDataOfId(String id) {
		boolean flag = false;
		if (id == null || "".equals(id)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ID_VALUE_NULL.getCode(),
					ExceptionCodeDes.ID_VALUE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;

	}

	/**
	 * xing_qi_accounttype表记录详情
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryAccountTypeInfoById(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingAccountTypeInfo info = gson.fromJson(body,
				XingAccountTypeInfo.class);
		String id = info.getId();
		boolean flag = checkDataOfId(id);
		if (flag) {
			XingAccountTypeInfo accountInfo = null;
			accountInfo = xingAccountTypeDAO.queryAccountTypeInfoById(id);
			if (accountInfo != null) {
				String resultBody = null;
				resultBody = gson.toJson(accountInfo);
				return resultBody;
			}
		}
		return null;
	}

	/**
	 * xing_qi_chargetype表记录详情
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 * @date 2012-12-28
	 */
	@Override
	public String queryChargetypeInfoById(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingChargeTypeInfo info = gson.fromJson(body, XingChargeTypeInfo.class);
		String id = info.getId();
		boolean flag = checkDataOfId(id);
		if (flag) {
			XingChargeTypeInfo chargeTypeInfo = null;
			chargeTypeInfo = xingChargeTypeDAO.queryChargeTypeById(id);
			if (chargeTypeInfo != null) {
				String resultBody = null;
				resultBody = gson.toJson(chargeTypeInfo);
				return resultBody;
			}
		}

		return null;
	}

	/**
	 * xing_qi_area_srv表记录详情
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 * @date 2012-12-28
	 */
	@Override
	public String queryAreaSrvInfoById(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingGameAreaSrvInfo info = gson.fromJson(body,
				XingGameAreaSrvInfo.class);
		String id = info.getId();
		boolean flag = checkDataOfId(id);
		if (flag) {
			XingGameAreaSrvInfo areaSrvInfo = null;
			areaSrvInfo = xingGameAreaSrvDAO.queryGameAreaSrvById(id);
			if (areaSrvInfo != null) {
				String resultBody = null;
				resultBody = gson.toJson(areaSrvInfo);
				return resultBody;
			}
		}
		return null;
	}

	/**
	 * xing_qi_game_topinfo表记录详情
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 * @date 2012-12-28
	 */
	@Override
	public String querygoodsTopInfoById(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingGoodsTopInfo info = gson.fromJson(body, XingGoodsTopInfo.class);
		String id = info.getId();
		boolean flag = checkDataOfId(id);
		if (flag) {
			XingGoodsTopInfo topInfo = null;
			topInfo = xingGoodsTopDAO.queryTopInfoById(id);
			if (topInfo != null) {
				String resultBody = null;
				resultBody = gson.toJson(topInfo);
				return resultBody;
			}
		}

		return null;
	}

	/**
	 * xing_qi_discount表记录详情
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 * @date 2012-12-28
	 */
	@Override
	public String queryDiscountInfoById(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		XingDisCountInfo info = gson.fromJson(body, XingDisCountInfo.class);
		String id = info.getId();
		boolean flag = checkDataOfId(id);
		if (flag) {
			XingDisCountInfo discountInfo = null;
			discountInfo = xingDisCountDAO.queryDisCountInfoByGoodsId(id);
			if (discountInfo != null) {
				String resultBody = null;
				resultBody = gson.toJson(discountInfo);
				return resultBody;
			}
		}

		return null;
	}

}
